package com.wt.struggle.goodbye.user.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.*
import com.wt.struggle.goodbye.info.FileInfo
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.ProUserInfo
import com.wt.struggle.goodbye.main.adapter.PicAdapter
import com.wt.struggle.goodbye.view.CustomPop
import com.xin.lv.yang.utils.activity.PictureSelectorActivity
import com.xin.lv.yang.utils.utils.DataUtil
import com.xin.lv.yang.utils.utils.FileUtils
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.recover_layout.*
import org.json.JSONObject
import java.lang.StringBuilder

/**
 * 私信或者删帖申请恢复
 */
class SiXinOrRecoverActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {
            Send.UPLOAD_PIC -> {
                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    val jsonObject = JSONObject(netInfo.dataResult)
                    val id = jsonObject.optInt("id")

                    picIdList.add(id)

                    update(id)

                }
            }

            Send.DELETE_RECYCLE_CODE -> {

                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    showToastShort("操作成功")
                    finish()
                }
            }
        }

    }

    var code: Int = 0
    var userInfo: ProUserInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.recover_layout)

        code = intent.getIntExtra("code", 0)

        if (code == 1) {
            tvTitle.text = "私信"
            buttonRecover.text = "发送私信"
            etContentText.hint = "请写点什么吧!!"
            tvTextTi.text = "私信"
            tvRight.visibility = View.GONE
            userInfo = intent.getParcelableExtra<ProUserInfo>("user")

        } else {

            tvTitle.text = "删帖恢复"
            etContentText.hint = "请输入删帖理由.."
            tvTextTi.text = "申诉内容"

        }

        imageBack.setOnClickListener {
            finish()
        }

        initPicAdapter()

        etContentText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {

            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                val content = etContentText.text.toString()
                tvTextLen.text = "${content.length}/200字"
            }

        })

        buttonRecover.setOnClickListener {
            if (code == 1) {
                saveSiXin()
            } else {
                save()
            }

        }
    }


    /**
     * 发送私信
     */
    private fun saveSiXin() {

        val content = etContentText.text.toString()

        when {
            content == "" -> showToastShort("请填写私信内容")

            else -> {
                val contentResult=DataUtil.getString(content)
                send!!.sendSiXin(userInfo!!.appUserId!!.toInt(), contentResult, buildPicStr(), handler)
                showLoadDialog()
            }
        }

    }

    fun save() {
        val content = etContentText.text.toString()
        when {
            content == "" -> showToastShort("请填写恢复帖子理由")
            picIdList.size == 0 -> showToastShort("请上传图片")
            else -> {
                val resultContent=DataUtil.getString(content)
                send!!.getRecoverTieList(resultContent, buildPicStr(), handler)
                showLoadDialog()
            }
        }

    }

    private fun buildPicStr(): String {
        val sb = StringBuilder()

        for (i in picIdList.indices) {
            sb.append(picIdList[i])
            if (i < picIdList.size - 1) {
                sb.append(",")
            }
        }
        return sb.toString()

    }

    val picIdList = arrayListOf<Int>()
    val picList = arrayListOf<FileInfo>()

    lateinit var adapter: PicAdapter

    private fun initPicAdapter() {

        val fileInfo = FileInfo()
        fileInfo.text = R.drawable.pic_add.toString()
        picList.add(fileInfo)

        addPicRecyclerView.layoutManager = GridLayoutManager(this, 3)
        adapter = PicAdapter(this, picList)
        adapter.code = 1
        addPicRecyclerView.adapter = adapter
        adapter.itemClickListener = object : ItemClickListener {
            override fun onItemClick(position: Int) {
                if (position == picList.size - 1) {
                    openChoose()
                }

            }

            override fun onLongClick(position: Int) {

            }

        }
    }

    fun update(id: Int) {
        val fileInfo = FileInfo()
        fileInfo.text = Config.GET_IMAGE_URL + id

        adapter.updateInfoNoCode(fileInfo)

    }


    private fun openChoose() {
        val customPop = CustomPop(this, 1)
        setAlpha(0.6f)
        customPop.show(object : CustomPop.OnCheckListener {
            override fun onCamera() {
                if (checkCameraPremission()) {
                    startActivityForResult(FileUtils.requestCamera(this@SiXinOrRecoverActivity), CustomPop.CAMERA_CODE)

                } else {
                    checkCamera()
                }

                customPop.dismiss()
                setAlpha(1f)
            }

            override fun onPhoto() {
                if (checkPhotoPremission()) {
                    startActivityForResult(
                        Intent(this@SiXinOrRecoverActivity, PictureSelectorActivity::class.java),
                        CustomPop.PHOTO_CODE
                    )

                } else {
                    checkPhoto()
                }

                customPop.dismiss()
                setAlpha(1f)
            }

            override fun onClose() {
                customPop.dismiss()
                setAlpha(1f)
            }

        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                CustomPop.CAMERA_CODE -> {
                    val imageFile = FileUtils.getImageFile()
                    if (imageFile.exists()) {
                        send!!.upImagePic(imageFile.absolutePath, Share.getId(this).toString(), handler!!)
                        showLoadDialog("上传中")
                    }
                }

                CustomPop.PHOTO_CODE -> {
                    val urlList = data!!.getParcelableArrayListExtra<Uri>(Intent.EXTRA_RETURN_RESULT)
                    showLoadDialog("上传中")

                    for (temp in urlList) {
                        send!!.upImagePic(temp.path, Share.getId(this).toString(), handler!!)
                    }
                }
            }
        }
    }
}